package com.cskaoyan.order.mq.promo;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderResponse;
import com.cskaoyan.order.service.OrderPromoService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @auther cskaoyan
 * @date 2022/7/19:11:27
 */
@Component
public class CreatePromoOrderConsumer {


    private DefaultMQPushConsumer consumer;

    @Autowired
    OrderPromoService orderPromoService;
    @PostConstruct
    public void init() {
       consumer = new DefaultMQPushConsumer("create_promo_order_consumer");

       consumer.setNamesrvAddr("127.0.0.1:9876");

        try {
            consumer.subscribe("create_promo_order", "*");

            consumer.setMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                    MessageExt message = msgs.get(0);
                    byte[] body = message.getBody();
                    String jsonStr = new String(body, 0, body.length, Charset.forName("utf-8"));
                    CreateSeckillOrderRequest createSeckillOrderRequest = JSON.parseObject(jsonStr, CreateSeckillOrderRequest.class);

                    CreateSeckillOrderResponse response = orderPromoService.createPromoOrder(createSeckillOrderRequest);
                    // 根据response的code判断是否消费成功
                    if(SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())){
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            });

            // 启动consumer
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
